<template>
  <div class="online-users-container">
    <div class="header-actions">
      <el-button type="primary" @click="$router.push('/user-profile')">
        查看用户画像分析
      </el-button>
    </div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>在线用户统计</span>
          <el-button type="primary" @click="refreshData">刷新</el-button>
        </div>
      </template>
      <div class="online-count">
        <el-statistic title="当前在线人数" :value="onlineCount">
          <template #suffix>
            <el-icon><User /></el-icon>
          </template>
        </el-statistic>
      </div>
      <el-table :data="onlineUsers" style="width: 100%; margin-top: 20px">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="loginTime" label="登录时间">
          <template #default="scope">
            {{ formatDate(scope.row.loginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="ipAddress" label="IP地址">
          <template #default="scope">
            {{ formatIp(scope.row.ipAddress) }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceInfo" label="设备信息">
          <template #default="scope">
            {{ formatDeviceInfo(scope.row.deviceInfo) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getOnlineUsers, getOnlineUserCount } from '@/api/auth'

const onlineUsers = ref([])
const onlineCount = ref(0)

const refreshData = async () => {
  try {
    // 并行获取在线用户列表和数量
    const [users, count] = await Promise.all([
      getOnlineUsers(),
      getOnlineUserCount()
    ])
    
    console.log('Online Users:', users)
    console.log('Online Count:', count)
    
    onlineUsers.value = users
    onlineCount.value = count
  } catch (error) {
    console.error('获取在线用户数据失败:', error)
    ElMessage.error('获取在线用户数据失败')
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateString
  }
}

const formatDeviceInfo = (deviceInfo) => {
  if (!deviceInfo) return '-'
  try {
    const browserMatch = deviceInfo.match(/(Chrome|Safari|Firefox|Edge|Edg)\/[\d.]+/)
    const osMatch = deviceInfo.match(/\((.*?)\)/)
    
    if (browserMatch && osMatch) {
      const browser = browserMatch[1]
      const os = osMatch[1].split(';')[0].trim()
      return `${browser} - ${os}`
    }
    return deviceInfo
  } catch (error) {
    console.error('设备信息格式化错误:', error)
    return deviceInfo
  }
}

const formatIp = (ip) => {
  if (!ip) return '-'
  return ip === '0:0:0:0:0:0:0:1' ? 'localhost' : ip
}

// 自动刷新数据（每30秒）
let refreshInterval

onMounted(() => {
  refreshData()
  refreshInterval = setInterval(refreshData, 30000)
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.online-users-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.online-count {
  text-align: center;
  margin: 20px 0;
}

.el-table {
  margin-top: 20px;
}

.header-actions {
  margin-bottom: 20px;
  text-align: right;
}
</style> 